package online.shenjian.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.enable", matchIfMissing = true)
public class HeaderExchangeConfig {

    @Bean
    public HeadersExchange headers() {
        return new HeadersExchange("headers");
    }

    private static class ConsumerConfig {

        @Bean
        public Queue headersAutoDeleteQueue1() {
            return new AnonymousQueue();
        }

        @Bean
        public Queue headersAutoDeleteQueue2() {
            return new AnonymousQueue();
        }

        @Bean
        public Queue headersAutoDeleteQueue3() {
            return new AnonymousQueue();
        }

        @Bean
        public Binding headersBinding1(HeadersExchange headers, Queue headersAutoDeleteQueue1) {
            Map<String, Object> headerMap = new HashMap<>();
            headerMap.put("h1", "Header1");
            headerMap.put("h2", "Header2");
            /**
             * 匹配到任意一个就发送至队列
             */
            return BindingBuilder.bind(headersAutoDeleteQueue1).to(headers).whereAny(headerMap).match();
        }

        @Bean
        public Binding headersBinding2(HeadersExchange headers, Queue headersAutoDeleteQueue2) {
            Map<String, Object> headerMap = new HashMap<>();
            headerMap.put("h1", "Header1");
            headerMap.put("h2", "Header2");
            /**
             * 全部匹配到才会发送至队列
             */
            return BindingBuilder.bind(headersAutoDeleteQueue2).to(headers).whereAll(headerMap).match();
        }

        @Bean
        public Binding headersBinding3(HeadersExchange headers, Queue headersAutoDeleteQueue3) {
            /**
             * 匹配到任意一个就发送至队列， 此处与headersBinding1一致，为了证明其也有fanout模式的功能
             */
            Map<String, Object> headerMap = new HashMap<>();
            headerMap.put("h1", "Header1");
            headerMap.put("h2", "Header2");
            return BindingBuilder.bind(headersAutoDeleteQueue3).to(headers).whereAny(headerMap).match();
        }
    }
}
